﻿//http启动脚本
"use strict";
const mvc         = require('cosjs.mvc');
const body        = require('body-parser');
const monitor     = require('cosjs.monitor');


module.exports = function(opts,httpServer){
    let app = this;
    let root = mvc.config.get("root");
/////////////////////HTTP服务//////////////////////
    app.defineHandlePrototype("model",mvc.model);
    app.defineHandlePrototype("config",mvc.config);
    app.defineHandlePrototype("library",mvc.library);
/////////////////////内部服务//////////////////////
    let jsonencoded = body.json({extended: true,limit:"100kb", });
    let local_root = root + '/handle/local';
    let local_route = {route:"/:branch/*",method:'all',output:'json',"subpath":local_handle_subpath}
    let local_server = app.server(local_root,local_route,jsonencoded);
    local_server.on('start',local_server_start);
    /////////////////////监控服务//////////////////////
    let spirit = mvc.config.get("spirit");
    if(spirit){
        create_spirit_server.call(local_server,spirit);
    }
};
function local_handle_subpath(){
    return this.req.params[0];
}

function local_server_start(){
    this.branch = this.req.params["branch"];
    if(!this.branch){
        return this.error("branch empty");
    }

    let branchModel = this.model.admin("branch");
    return branchModel.get(this.branch,["_id","secret"]).then(data=>{
        if(!data){
            return this.error("branch not exist",this.branch);
        }
        let secret = data["secret"];
        let {err,ret} =  this.library.call(this,'sign/verify',this.req.body,secret);
        if(err){
            return this.error(err,ret);
        }
    })
}

function create_spirit_server(spirit){
    let server = spirit.server;
    server.secret = mvc.config.get('secret');

    Promise.resolve().then(()=>{
        let branch = mvc.model.admin("branch");
        return branch.get(null,['_id',"name"]);
    }).then(ret=>{
        let key = Object.keys(ret);
        if(key.length < 1){
            return Promise.reject("branch empty")
        }
        server.branch = key.join(',');
        let update = spirit.update;
        update.sid = [];
        update.url = mvc.config.get('remote.url')||'';
        update.local = mvc.config.get('local.port');
        update.remote = mvc.config.get('remote.port')||80;

        return monitor.spirit(server,update);
    }).then(()=>{
        this.loader.addFile(monitor.handle,spirit.route);
    }).catch(err=>{
        console.log("create_spirit_server",err)
    })
}